<template>
  <div class="app-container">
    <el-row type="flex" justify="center">
      <el-col :span="20" style="text-align: center">
        <h1>{{knowledgeForm.title}}</h1>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="20">
        <Editor
          style="margin-left: 50px; margin-right: 50px; margin-bottom: 30px; border: 1px"
          v-model="wangEditor.html"
          :defaultConfig="wangEditor.editorConfig"
          :mode="wangEditor.mode"
          @onCreated="setEditorReadOnly"
        />
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="20">
        <el-link
          v-for="attach in knowledgeForm.attachList"
          type="primary"
          :href="attach.url"
          target="_blank"
          style="margin-left: 60px; margin-top: -30px"
          >
          {{attach.fileName}}
        </el-link>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import "@wangeditor/editor/dist/css/style.css"
import { insertKnowledge, selectKnowledgeById, updateKnowledge, uploadAttachFile } from '@/api/knowledge/knowledge'
import { getToken } from '@/utils/auth'

export default {
  name: 'view',
  components: {
    Editor,
    Toolbar
  },
  data() {
    return {
      // 是否正在编辑
      editing: false,
      // 表单
      knowledgeForm: {
        id: '',
        type: '',
        title: '',
        keywords: '',
        isPublic: true,
        content: '',
        attachList: []
      },
      // 所属分类选项
      typeOptions: [],
      // 富文本编辑器配置信息
      wangEditor: {
        editor: null,
        html: '',
        toolbarConfig: {
          excludeKeys: [
            'insertImage',
            'insertVideo',
            'fullScreen'
          ]
        },
        editorConfig: {
          placeholder: '',
          MENU_CONF: {
            uploadImage: {
              server: process.env.VUE_APP_BASE_API + '/knowledge/uploadFile',
              fieldName: 'file',
              maxFileSize: 10 * 1024 * 1024,
              maxNumberOfFiles: 10,
              headers: {
                Accept: 'application/json;charset=UTF-8',
                Authorization: getToken()
              },
              withCredentials: true,
              timeout: 10 * 1000,
              onBeforeUpload(files){
                Message({
                  message: '图片正在上传中,请耐心等待',
                  duration: 0,
                  customClass: 'uploadTip',
                  iconClass: 'el-icon-loading',
                  showClose: true
                });
                return files;
              },
              onDelete(file){
                console.log('dsdsdsdsdsds')
              },
              // 自定义插入图片
              customInsert(res, insertFn) {
                console.log('res = ' + JSON.stringify(res))
                // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
                // 先关闭等待的Message
                Message.closeAll();
                if (res.code === 200) {
                  Message.success({
                    message: `${res.data.originalName} 上传成功`
                  });
                } else {
                  Message.error({
                    message: `${res.data.originalName} 上传失败，请重新尝试`
                  });
                }
                insertFn(res.data.link, res.data.name, res.data.link);
              },
              // 单个文件上传成功之后
              onSuccess(file, res) {
                console.log(`${file.name} 上传成功`, res);
              },

              // 单个文件上传失败
              onFailed(file, res) {
                console.log(`${file.name} 上传失败`, res);
              },

              // 上传进度的回调函数
              onProgress(progress) {
                console.log('progress', progress);
                // progress 是 0-100 的数字
              },

              // 上传错误，或者触发 timeout 超时
              onError(file, err, res) {
                console.log(`${file.name} 上传出错`, err, res);
                Message.closeAll();
                Message.error({
                  message: `${file.name} 上传出错`
                });
              }
            },
            uploadVideo: {
              server: process.env.VUE_APP_BASE_API + '/knowledge/uploadFile',
              fieldName: 'file',
              maxFileSize: 50 * 1024 * 1024,
              maxNumberOfFiles: 3,
              headers: {
                Accept: 'application/json;charset=UTF-8',
                Authorization: getToken()
              },
              withCredentials: true,
              timeout: 1000 * 1000,
              onBeforeUpload(files){
                Message({
                  message: '视频正在上传中,请耐心等待',
                  duration: 0,
                  customClass: 'uploadTip',
                  iconClass: 'el-icon-loading',
                  showClose: true
                });
                return files;
              },
              // 自定义插入视频
              customInsert(res, insertFn) {
                console.log('res = ' + JSON.stringify(res))
                // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
                // 先关闭等待的Message
                Message.closeAll();
                if (res.code === 200) {
                  Message.success({
                    message: `${res.data.originalName} 上传成功`
                  });
                } else {
                  Message.error({
                    message: `${res.data.originalName} 上传失败，请重新尝试`
                  });
                }
                insertFn(res.data.link, res.data.name, res.data.link);
              },
              // 单个文件上传成功之后
              onSuccess(file, res) {
                console.log(`${file.name} 上传成功`, res);
              },

              // 单个文件上传失败
              onFailed(file, res) {
                console.log(`${file.name} 上传失败`, res);
              },

              // 上传进度的回调函数
              onProgress(progress) {
                console.log('progress', progress);
                // progress 是 0-100 的数字
              },

              // 上传错误，或者触发 timeout 超时
              onError(file, err, res) {
                console.log(`${file.name} 上传出错`, err, res);
                Message.closeAll();
                Message.error({
                  message: `${file.name} 上传出错`
                });
              }
            }
          }
        },
        mode: 'default'
      },
      // 附件列表
      attachFileList: [],
    }
  },
  mounted() {
    this.knowledgeForm.id =this.$route.query.id
    if(this.knowledgeForm.id != null && this.knowledgeForm.id != undefined) {
      selectKnowledgeById(this.knowledgeForm.id).then(response => {
        this.knowledgeForm = response.data
        document.title = this.knowledgeForm.title
        if (this.knowledgeForm.isPublic === '1') {
          this.knowledgeForm.isPublic = true
        } else {
          this.knowledgeForm.isPublic = false
        }
        this.wangEditor.html = this.knowledgeForm.content
        this.attachFileList = []
        if (response.data.attachList != null && response.data.attachList.length > 0) {
          response.data.attachList.forEach(f => {
            let a = {}
            a.name = f.fileName
            a.url = f.url
            this.attachFileList.push(a)
          })
        }
        this.showDialog = true
      })
    }
  },
  methods: {
    onEditorCreated(editor){
      this.wangEditor.editor = Object.seal(editor)
    },
    setEditorReadOnly(editor){
      this.wangEditor.editor = Object.seal(editor)
      this.wangEditor.editor.disable()
    },
  },
  beforeDestroy() {
    const editor = this.wangEditor.editor
    if(editor == null) return
    editor.destroy()
  }
}
</script>

<style scoped lang="scss">

</style>
